package com.zhixing.order.websocket;

import com.zhixing.order.domain.vo.OrderGrabInfoVO;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static com.zhixing.common.constant.Constant.ZHIXING_DRIVER_WEBSOCKET;

@Slf4j
@Component
@ServerEndpoint(value = "/ws/driver/{driverId}", encoders = {DriverWebSocketEncoder.class})
public class DriverWebSocket {

    private static String instanceId;
    private static RedisTemplate<String, Object> redisTemplate;
    private final static Map<Integer, Session> map = new ConcurrentHashMap<>();

    @Autowired
    public void setInstanceId(@Value("${spring.application.instance-id}") String instanceId) {
        DriverWebSocket.instanceId = instanceId;
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        DriverWebSocket.redisTemplate = redisTemplate;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("driverId") Integer driverId) {
        log.info("websocket服务连接，司机websocket连接，司机id：{}", driverId);
        map.put(driverId, session);
        redisTemplate.opsForHash().put(ZHIXING_DRIVER_WEBSOCKET, driverId, instanceId);
    }

    @OnClose
    public void onClose(@PathParam("driverId") Integer driverId) {
        log.info("websocket服务关闭，司机websocket关闭，司机id：{}", driverId);
        map.remove(driverId);
        redisTemplate.opsForHash().delete(ZHIXING_DRIVER_WEBSOCKET, driverId);
    }

    @OnError
    public void onError(@PathParam("driverId") Integer driverId, Throwable throwable) {
        log.info("websocket服务连接错误，司机websocket错误，司机id：{}", driverId);
        map.remove(driverId);
        redisTemplate.opsForHash().delete(ZHIXING_DRIVER_WEBSOCKET, driverId);
        throwable.printStackTrace();
    }

    public void sendMessage(OrderGrabInfoVO orderGrabInfoVO) {
        String id = (String) redisTemplate.opsForHash().get(ZHIXING_DRIVER_WEBSOCKET, orderGrabInfoVO.getDriverId());
        Session session = map.get(orderGrabInfoVO.getDriverId());
        if (id != null && session != null) session.getAsyncRemote().sendObject(orderGrabInfoVO);
    }
}
